import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { map } from 'rxjs/operators';

import { pb } from 'src/pb';

@Injectable({
  providedIn: 'root'
})
export class FileService {

  constructor(
    private http: HttpClient,
  ) { }

  folder(id = '0', offset = 0) {
    return this.http.get(`/api/file/folder/${id}?offset=${offset}`, {
      responseType: 'arraybuffer'
    })
      .pipe(map(ab => pb.Folder.decode(new Uint8Array(ab as ArrayBuffer))))
      .toPromise();
  }

  file(id: string) {
    return this.http.get(`/api/file/info/${id}`, {
      responseType: 'arraybuffer'
    })
      .pipe(map(ab => pb.FileInfo.decode(new Uint8Array(ab as ArrayBuffer))))
      .toPromise();
  }

  text(id: string, offset = 0, page = '') {
    return this.http.get(`/api/file/text/${id}?offset=${offset}${page ? '&' + page : ''}`, {
      responseType: 'arraybuffer'
    })
      .pipe(
        map(ab => pb.Text.decode(new Uint8Array(ab as ArrayBuffer))),
      )
      .toPromise();
  }

}
